Start a Mosquitto container first. For example:

  • Use codes\_demo\1_start_broker.sh to start a Mosquitto container on Raspberry Pi.
  • Config files are in mqtt_config\mqtt.
  • set allow_anonymous true in mqtt_config\mqtt\config\mosquitto.conf to allow anonymous client.

Getting Started

This script only work with MicroPython.
Using MQTT client module for MicroPython.


In [ ]:
import time
import config
import worker_config

host = config.BROKER_HOST
port = config.HUB_PORT
topic_root = "test"
client_id = worker_config.WORKER_NAME
auth = {'username': config.USERNAME,
        'password': config.PASSWORD}
qos_level = config.QOS_LEVEL


import simple as mqtt
# import robust as mqtt

client = mqtt.MQTTClient(client_id = client_id, 
                         server = host, 
                         port = port, 
                         user = config.USERNAME, 
                         password = config.PASSWORD, 
                         keepalive = 60,
                         ssl = False, ssl_params = {})


topic = topic_root
msg = 'last will'
client.set_last_will(topic, msg, retain = False, qos = 1)

client.connect(clean_session = True)
client.ping()


# _________________________________________
def on_message(topic, msg):
    print('Message topic: {}, payload: {}'.format(topic, str(msg)))
#     print('Message:\n{}\n'.format(msg.__dict__))

client.set_callback(on_message)    
client.subscribe(topic_root, qos = 1) 
# client.subscribe("$SYS/broker/messages/#", qos = 1) 
# client.subscribe("$SYS/broker/clients/connected", qos = 1) 
client.subscribe('$SYS/broker/log/#', qos = 1)

topic = topic_root
msg = 'Hello world'
client.publish(topic, msg, retain = False, qos = 1)

while True:
    time.sleep(1)
    client.wait_msg()
    client.check_msg()

In [ ]:
client.disconnect()
client = None